package com.example.onlineanswer.common.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmailUtil {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.nickname:在线知识竞赛系统}")
    private String nickname;

    /**
     * 发送验证码邮件
     *
     * @param to        收件人
     * @param verifyCode 验证码
     * @return 是否发送成功
     */
    public boolean sendVerifyCodeEmail(String to, String verifyCode) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 设置发件人
            helper.setFrom(String.format("%s <%s>", nickname, from));
            // 设置收件人
            helper.setTo(to);
            // 设置邮件主题
            helper.setSubject("在线知识竞赛系统 - 注册验证码");

            // 使用Thymeleaf模板引擎渲染邮件内容
            Context context = new Context();
            context.setVariable("verifyCode", verifyCode);
            String content = templateEngine.process("email/verify-code", context);
            
            // 设置邮件内容，并指定为HTML格式
            helper.setText(content, true);
            
            // 发送邮件
            mailSender.send(message);
            
            log.info("验证码邮件发送成功，收件人：{}", to);
            return true;
        } catch (MessagingException e) {
            log.error("验证码邮件发送失败，收件人：{}，错误信息：{}", to, e.getMessage(), e);
            return false;
        }
    }
} 